<template>
  <div class="warehouse-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="店铺编码">
          <el-input v-model="searchForm.shopCode" placeholder="请输入店铺编码" />
        </el-form-item>
        <el-form-item label="店铺名称">
          <el-input v-model="searchForm.shopName" placeholder="请输入店铺名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">新增店铺</el-button>
      <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="shopCode" label="店铺编码" width="120" />
      <el-table-column prop="shopName" label="店铺名称" width="150" />
      <el-table-column prop="ownerName" label="负责人" width="120" />
      <el-table-column prop="contactNumber" label="联系电话" width="120" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增店铺' : '编辑店铺'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="店铺编码" prop="shopCode">
          <el-input v-model="formData.shopCode" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="店铺名称" prop="shopName">
          <el-input v-model="formData.shopName" />
        </el-form-item>
        <el-form-item label="负责人" prop="ownerName">
          <el-input v-model="formData.ownerName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="formData.contactNumber" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { shopApi } from '../../../api'

// 搜索表单
const searchForm = reactive({
  shopCode: '',
  shopName: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const dialogTitle = computed(() => dialogType.value === 'add' ? '新增店铺' : '编辑店铺')
const formRef = ref(null)

// 表单数据
const formData = reactive({
  id: '',
  shopCode: '',
  shopName: '',
  ownerName: '',
  contactNumber: '',
  status: 1,
  remark: ''
})

// 表单校验规则
const rules = {
  shopCode: [
    { required: true, message: '请输入店铺编码', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  shopName: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' }
  ],
  ownerName: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    console.log('请求参数：', params)

    const res = await shopApi.getList(params)
    console.log('API返回数据：', res)
    
    tableData.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('获取数据错误：', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await shopApi.add(formData)
      ElMessage.success('添加成功')
    } else {
      await shopApi.update(formData)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    getTableData()
  } catch (error) {
    console.error('提交失败：', error)
    ElMessage.error('提交失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该店铺吗？', '提示', {
      type: 'warning'
    })
    
    await shopApi.delete(row.id)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的店铺')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 个店铺吗？`,
      '提示',
      { type: 'warning' }
    )
    
    const ids = selectedRows.value.map(row => row.id)
    console.log('ids',ids)
    await shopApi.batchDelete(ids)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败：', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  getTableData()
}

// 新增店铺
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单数据
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'status' ? 1 : ''
  })
  // 等待 DOM 更新后重置表单验证
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 编辑店铺
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  // 复制数据到表单
  Object.keys(formData).forEach(key => {
    formData[key] = row[key]
  })
  // 等待 DOM 更新后重置表单验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
}

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
  console.log('已选择的行：', rows)
}

// 初始化
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.warehouse-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.unit-label {
  margin-left: 10px;
  color: #666;
}
</style> 